//
//  CoreDataManager.m
//  Puzzle_Crazy
//
//  Created by VIETHUNG on 4/2/14.
//  Copyright (c) 2014 DanielLe. All rights reserved.
//

#import "CoreDataManager.h"
#import "Puzzle.h"
#import "PuzzleObject.h"

static CoreDataManager *coreDataManager;
@implementation CoreDataManager

+ (CoreDataManager *)sharedManager
{
    if (!coreDataManager) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            coreDataManager = [[CoreDataManager alloc] init];
        });
        
    }
    return coreDataManager;
}

- (NSManagedObjectContext *) managedObjectContext {
    
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    return managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel {
    
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Puzzle" withExtension:@"momd"];
    managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Puzzle.sqlite"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) {
        NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Puzzle" ofType:@"sqlite"]];
        
        NSError* err = nil;
        
        if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err]) {
            NSLog(@"Oops, could copy preloaded data");
        }
    }
    
    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return persistentStoreCoordinator;
}

- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (void)saveData:(NSMutableArray*)arrayData
{
    NSManagedObjectContext *context = [self managedObjectContext];
    
    for (PuzzleObject *puzzleObj in arrayData) {
        Puzzle *puzzle =  [NSEntityDescription insertNewObjectForEntityForName:@"Puzzle" inManagedObjectContext:context];
        puzzle.image    = puzzleObj.Objimage;
        puzzle.easy     = puzzleObj.Objeasy;
        puzzle.medium   = puzzleObj.Objmedium;
        puzzle.hard     = puzzleObj.Objhard;
    }
    
    NSError *error;
    // here's where the actual save happens, and if it doesn't we print something out to the console
    if (![context save:&error])
    {
        NSLog(@"Problem saving: %@", [error localizedDescription]);
    }
}

- (void)deleteData
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSError *error;
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Puzzle" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    for (Puzzle *puzzle in fetchedObjects)
    {
        [context deleteObject:puzzle];
    }
    [context save:&error];
    [context reset];
}

- (NSMutableArray*)showData
{
    NSMutableArray *arrayData = [NSMutableArray array];
    NSManagedObjectContext *context = [self managedObjectContext];
    NSError *error;
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Puzzle" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    for (Puzzle *puzzle in fetchedObjects) {
        PuzzleObject *puzzleObject = [[PuzzleObject alloc] init];
        puzzleObject.Objimage   = puzzle.image;
        puzzleObject.Objeasy    = puzzle.easy;
        puzzleObject.Objmedium  = puzzle.medium;
        puzzleObject.Objhard    = puzzle.hard;
        
        [arrayData addObject:puzzleObject];
    }
    
    return arrayData;
}

- (void)updateData:(PuzzleObject *)puzzleObj
{
//    NSManagedObjectContext *context = [self managedObjectContext];
    
}

@end
